const db=uniCloud.database()
import {adjustArrayOrder} from '@/utils/common.js'

export default {
    namespaced: true,
    state: {
		// 表头数据
		tableHeard: [],
		// 需要展示的表头
		showTableHeard:[],
		// 表格数据
        thread_tree_data: [],
		// 总条数
		total: 1,
		// 当前页码
		current: 1,
		// 每页多少条数据
		pageSize: 5,
		// 当前选中的客户数据
		clientInfo:{},
		// popup状态,无论true或false，一旦改变
		showPopup: false,
		// 当前跟进记录的数据
		followRecord:[],
		// 现有搜索条件
		params:'',
		// 数据请求状态
		isReqState: false,
		// 基础搜索条件
		baseCondition:'',
		// 页面栈
		page: '',
		// Hint组件数据
		hintData:[],
		// Hint组件提示信息
		showHintInfo: false
    },
    mutations: {
		
		// 修改表格、表头数据、分页器总数
		setThreadData(state, data) {
			state.thread_tree_data = data.data;
			state.total = data.count; 
			state.tableHeard = ["index","name","sex","phone","age","demand","city","education","identity","work","income","credit","certification","remark","upload_time","operation"]
		}, 
		
		// 修改表格选中行的数据
		setClientInfo(state, data) {
			state.showPopup = !state.showPopup
			state.clientInfo = data; 
		},
		
		// 删除当前跟进记录（重新赋值）
		removeFollowRecord(state) {
			state.followRecord = []
		},
		
		// 修改当前选中行的跟进记录
		setFollowRecord(state, data) {
			state.followRecord = data
		},
		
		// 跟进输入框数据
		// setFollowInfo(state) {
		// 	state.followInfo = ''
		// },
		
		// 保存现有搜索条件
		saveParams(state, data){
			state.params = data
		},
		
		// 修改页码
		setCurrent(state, data){
			state.current = data
		},
		
		// 修改每页多少条数据
		setPageSize(state, data){
			state.pageSize = data
		},
		
		// 修改Hint提示组件数据
		setHintData(state, data){
			state.hintData = data
		},
		
		// 修改Hint提示组件数据
		setShowHintInfo(state, data){
			state.showHintInfo = data
		},
		
		// 修改请求状态
		setIsReqState(state){
			state.isReqState = !state.isReqState
		},
		
		// 修改基础搜索条件
		setBaseCondition(state,data){
			console.log(data);
			if(state.page !== data){
				state.current = 1
				state.page = data
			}
			if(data === 'data'){
				// 7天内，正常用户
				state.baseCondition = 'latestTime >' + (Date.now() - (7*24*60*60*1000)) + ' && clientStatus == 0'
			}else if(data === 'pool'){
				// 超过7天，正常用户
				state.baseCondition = 'latestTime <' + (Date.now() - (7*24*60*60*1000)) + ' && clientStatus == 0'
			}else{
				// 删除的用户
				state.baseCondition = 'clientStatus == 1'
			}
		}
		
    },
    actions: {
		// 整理搜索条件
		async getThreadData({dispatch, commit, state}, params = {}) {
			let condition = state.baseCondition
			for(let key in params ){
				if(key == 'name'){
					condition += ' && ' + `/${params[key]}/.test(name)`
				}else if(typeof params[key] === 'number'){
					condition += ' && ' + key + '==' +  params[key]
				}else if(typeof params[key] === 'object'){
					condition += ' && ' + key + ' in [' +  params[key] + ']'
				}else if(typeof params[key] === 'string'){
					condition += ' && ' + key + '=="' +  params[key] + '"'
				}
			}
			console.log(condition);
			dispatch('reqGetThreaData', condition)
			
		},
		
		// 获取客户数据
		async reqGetThreaData({commit, state}, condition=''){
			if(condition){
				commit('saveParams', condition)
			}else{
				condition = state.params
			}
			// 表格提示状态
			commit('setIsReqState')
			db.collection('zf_customerInfo')
				.where(condition)
				.skip((state.current-1) * state.pageSize)
				.limit(state.pageSize)
				.get({getCount:true})
				.then(res => {
					console.log(res);
					if (res.errCode==0 && res.result.data.length > 0) {  
						commit('setThreadData', res.result);
					}else if(res.errCode==0){
						commit('setThreadData', res.result);
						uni.showToast({ title: "暂无数据", icon: "none" })
					}
				})
				.catch(err => {  
					console.log(err)
					uni.showToast({ title: "表格数据获取失败", icon: "none" })
				})
				.finally(()=>{
					commit('setIsReqState')
				})
		},
		
		// 获取统计个数
		async getCount({commit, state}) {
			
			let condition = 'latestTime >' + (Date.now() - (7*86400000)) + ' && clientStatus == 0'
			
			let arr = []
			// 三天以上未跟进
			arr.push( condition + ' && ' + 'latestTime <=' + (Date.now() - (3*86400000)) )
			// 五天以上未跟进
			arr.push( condition + ' && ' + 'latestTime <=' + (Date.now() - (5*86400000)) )
			// 即将被回收（6天），3星以上
			arr.push( condition + ' && ' + 'latestTime <=' + (Date.now() - (6*86400000)) + '&&' + 'class >= 3' )
			// 即将被回收（6天）
			arr.push( condition + ' && ' + 'latestTime <=' + (Date.now() - (6*86400000)) )
			// 未跟进
			arr.push( condition + ' && ' + 'timestamp === latestTime' )
			
			let results = arr.map( async item => {
				return await db.collection('zf_customerInfo')
					.where(item)
				    .count()
			})
			
			Promise.all(results).then( res => {
				console.log(res);
				
				commit('setHintData', res.map(item => item.result.total));
				res.forEach(item=>{
					console.log(item.result.total);
				})
				// console.log(res.result.total)
			})
			
		},
		
		
		// 提交跟进记录
		async addFollowRecord({commit, state, dispatch}, obj = {}){
			// 1、获取当前客户对应的跟进记录
			let res = await db.collection('zf_client_followRecord').where({ client_id: state.clientInfo._id }).get()
			
			obj.client_id = state.clientInfo._id
			
			return new Promise( (resolve, reject) =>{
				db.collection('zf_client_followRecord').add(obj).then(async res=>{
					// commit('setFollowInfo')
					await dispatch('getFollowRecord')
					resolve(res)
				}).catch(err=>{
					reject(err)
				})
			})
			
		},
		
		// 获取跟进记录
		async getFollowRecord({ commit, state}){
			// console.log(uniCloud.getCurrentUserInfo());
			uni.showLoading()
			const followRecordTemp = db.collection('zf_client_followRecord').getTemp()
			const userInfoTemp = db.collection('uni-id-users').field('_id,nickname').getTemp() 
			
			await db.collection(followRecordTemp, userInfoTemp).where({
				client_id:state.clientInfo._id,
			}).orderBy('follow_date desc').get().then(res=>{
				console.log(res);
				if(res.errCode === 0){
					commit('setFollowRecord', res.result.data)
				}
			}).catch(err=>{
				console.log(err)
			})
			uni.hideLoading()
		},
		
		// popup保存，添加用户信息
		savePopup({commit, dispatch, state}, params){
			let {_id, ...data} = { ...params }
			db.collection('zf_customerInfo')
				.doc( params._id )
				.update( data )
				.then(res=>{
					uni.showToast({
						title: "修改成功",
						icon: "none"
					})
					dispatch('getThreadData')
					
				})
				.catch(err=>{
					console.log(err);
					uni.showToast({
						title: "修改失败",
						icon: "none"
					})
				})
		},
		
    }
}


